<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>班组管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<link rel="stylesheet" href="${pageContext.request.contextPath }/assets/css/layui.css"  media="all">
	<link rel="stylesheet" href="${pageContext.request.contextPath }/assets/css/toastr.min.css"  media="all">
</head>
<body>
	<!-- 点击行的时候，把行ID存入 -->
	<input class="layui-hide" id="tidtest">
	
	<div class="demoTable" style="padding:10px 0 0 15px">
    	<div class="layui-inline">
        	<input class="layui-input" name="keyWord" id="keyWord" placeholder="请输入班组名称" autocomplete="off">
    	</div> &nbsp; &nbsp; &nbsp; &nbsp;
    	<button class="layui-btn layui-btn-blue" style="margin: 0 0 0 10px" data-type="reload"><i class="layui-icon layui-icon-search">  搜索</i></button>
	</div>
	
	<!-- 页面班组表 -->
	<table class="layui-hide" id="test" lay-filter="test"></table>
	<!-- 页面班组的员工表 -->
	<table class="layui-hide" id="testDetial" lay-filter="testDetial"></table>
	
	<!-- 班组弹框表单 -->
	<div id="formDiv" hidden>
	<form class="layui-form" id="addform">
		<input type="hidden" id="tid" name="tid">
		<br>
		<div class="layui-form-item">
			<div class="layui-inline">
		      <label class="layui-form-label" style="margin-left: 50px;">班组名称</label>
		      <div class="layui-input-inline">
		        <input lay-verify="tname" class="layui-input" onfocus="editValue()" type="text" id="tname" name="tname" style="width:200px">
		      </div>
		    </div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label" style="margin-left: 50px;">班组编号</label><input lay-verify="tnumber" class="layui-input" type="text" id="tnumber" name="tnumber" style="width:200px">
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
		      <label class="layui-form-label" style="margin-left: 50px;">班组长</label>
		      <div class="layui-input-inline" style="width:200px">
		      	<select id="num" name="num" class="layui-input" lay-filter="num" lay-verify="num">
					<option value="">请选择班组长</option>
					<c:forEach items="${allUser }" var="user">
						<option value="${user.uid }">${user.userName }</option>
					</c:forEach>
				</select>
		      </div>
		    </div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
		      <label class="layui-form-label" style="margin-left: 50px;">班次</label>
		      <div class="layui-input-inline" style="width:200px">
		      	<select id="crew" name="crew" class="layui-input" lay-search="" lay-verify="crew" onclick="getClasses()">
					<option value="">请选择班次</option>
					<c:forEach items="${allClasses }" var="classes">
						<option value="${classes.className }">${classes.className }</option>
					</c:forEach>
				</select>
		      </div>
		    </div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label" style="margin-left: 50px;">备注</label><input lay-verify="remarks" class="layui-input" type="text" id="remarks" name="remarks" style="width:200px">
			<br>
		</div>
		<div class="layui-form-item">
			<button class="layui-btn layui-btn-blue" id="submit" lay-submit lay-filter="addform" style="margin-left:140px">提交</button>
			<button type="reset" class="layui-btn layui-btn-primary">重置</button>
		</div>
	</form>
</div>

 <!-- 员工弹框表单 -->
<div id="formDiv2" hidden>
	<form class="layui-form" id="addform2">
		<br>
		<input type="hidden" id="id" name="id">
		<div class="layui-form-item">
			<div class="layui-inline">
		      <label class="layui-form-label" style="margin-left: 50px;">员工</label>
		      <div class="layui-input-inline" style="width:200px">
		     	<select id="uid" name="uid" onfocus="editValue()" class="layui-input" lay-search="" lay-verify="uid">
					<option value="">请选择员工</option>
					<c:forEach items="${allUser }" var="user">
						<option value="${user.uid }">${user.userName }</option>
					</c:forEach>
				</select>
		      </div>
		    </div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		
		<div class="layui-form-item">
			<div class="layui-inline">
		      <label class="layui-form-label" style="margin-left: 50px;">班组</label>
		      <div class="layui-input-inline" style="width:200px">
		     	<select id="tid" name="tid" onfocus="editValue()" class="layui-input" lay-search="" lay-verify="tid">
					<option value="">请选择班组</option>
					<c:forEach items="${allTeam }" var="team">
						<option value="${team.tid }">${team.tname }</option>
					</c:forEach>
				</select>
		      </div>
		    </div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		<button class="layui-btn layui-btn-blue" lay-submit lay-filter="addform2" style="margin-left:140px">提交</button>&emsp;&emsp;&emsp;&emsp;<button type="reset" class="layui-btn layui-btn-primary">重置</button>
	</form>
</div>

 <!-- 班组表格的新增，删除 -->
<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container">
		<button class="layui-btn layui-btn-blue" lay-event="add"><i class="layui-icon layui-icon-add-1">  新增</i></button>
		<button class="layui-btn layui-btn-blue" lay-event="delete"><i class="layui-icon layui-icon-delete">批量删除</i></button>
	</div>
</script>
 
 <!-- 班组表格的编辑 -->
<script type="text/html" id="barDemo">
	<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 员工表格的新增 -->
<script type="text/html" id="toolbarDemo3">
	<div class="layui-btn-container">
		<button class="layui-btn layui-btn-blue" lay-event="add"><i class="layui-icon layui-icon-add-1">  新增</i></button>
		<button class="layui-btn layui-btn-blue" lay-event="delete"><i class="layui-icon layui-icon-delete">批量删除</i></button>
	</div>
</script>

<!-- 员工表格的编辑 -->
<script type="text/html" id="toolbarDemo2">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
              
<script src="${pageContext.request.contextPath }/assets/layui.js" charset="utf-8"></script>
<script src="${pageContext.request.contextPath }/assets/layui.all.js"></script>
<script src="${pageContext.request.contextPath }/assets/js/jquery.min.js" charset="utf-8"></script>
<script src="${pageContext.request.contextPath }/assets/js/toastr.min.js" charset="utf-8"></script>

<script>
layui.use(['table','layer','upload','form'], function(){
	var table = layui.table;
	var layer = layui.layer,
    form = layui.form;
	
	var $ = layui.jquery, active = {
			reload:function () {
				var tname = $("#keyWord").val();
				table.reload('contenttable',{
					method:'get',
					where:{tname: tname},
					page:{
						curr:1  //重新从第一页开始
					}
				}); 
			}
		}
	$('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
	
	table.render({
	    elem: '#test'
	    ,url:'${pageContext.request.contextPath }/teamMana/listPageTeam.do'
	    ,toolbar: '#toolbarDemo'
	    ,title: '班组管理'
	    ,id :'contenttable'
	    ,limits:[10,20,30]
	    ,cols: [[
	    	{type: 'checkbox', fixed: 'left'}
	    	,{field:'', title:'序号', sort: true, type:'numbers', width: 60}
	      	,{field:'tname', title:'班组名称'}
	      	,{field:'tnumber', title:'班组编号'}
	      	,{field:'foreman', title:'班组长'}
	      	,{field:'crew', title:'班次'}
	      	,{field:'remarks', title:'备注'}
	      	,{fixed: 'right', title:'操作',  width: 130, toolbar: '#barDemo'}
	    ]]
	    ,page: true
	});
  
	//监听行单击事件(子表)
	 table.on('row(test)', function(obj){
		$("#tidtest").val(obj.data.tid);
	  	table.render({
		    elem: '#testDetial'
		    ,url:'${pageContext.request.contextPath }/teamMana/listPageUserByTeam.do'
		    ,toolbar: '#toolbarDemo3'
		    ,where:{tid: obj.data.tid}
		    ,title: '班组的员工详情数据表'
		    ,id :'contentDetialTable'
		    ,limits:[10,20,30]
		    ,cols: [[
		    	{type: 'checkbox', fixed: 'left'}
		    	,{type: 'numbers', fixed: 'left', title:'序号'}
		    	,{field:'account', title:'工号'}
			    ,{field:'userName', title:'姓名'}
			    ,{field:'six', title:'性别'}
			    ,{field:'birthday', title:'生日'}
			    ,{field:'phone', title:'联系方式'}
			    ,{field:'qq', title:'qq'}
			    ,{fixed: 'right', title:'操作',  width: 130, toolbar: '#toolbarDemo2'}
		    ]]
		    ,page: true
		});
	});
	
	//员工表的新增，删除
	table.on('toolbar(testDetial)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
	    switch(obj.event){
	    	case 'add':
	    		layer.open({
					  type: 1 		//Page层类型
					  ,area: ['500px', '550px'] //宽  高
					  ,title: '新增'
					  ,shade: 0.1 	//遮罩透明度
					  ,shadeClose: true //点击遮罩关闭
					  ,maxmin: true //允许全屏最小化
					  ,anim: 1 		//0-6的动画形式，-1不开启
					  ,content: $('#formDiv2')
					  ,success: function () {
						  document.getElementById("addform2").reset();
					 	  $('#id').val('');
					  }
					  ,end: function () {
						  var formDiv = document.getElementById('formDiv2');
						  formDiv.style.display = '';
					  }
					});
	      	break;
	    	case 'delete':
	        	var data = checkStatus.data;
	        	var str = "";
	        	if(data.length==0){
	        		toastr.warning("请至少选择一条记录！");
	        	}else{
	        		for(var i=0;i<data.length;i++){
		        		str += data[i].id;
		        		if(i != data.length-1){
		        			str += ",";
		        		}
		        	}
		        	layer.confirm('确定删除吗？', function(index){
	    				$.ajax({
	    			    	type:'post',
	    			    	url:'${pageContext.request.contextPath }/empMana/deleteEmp.do',
	    			    	data:{"str":str},
	    			    	dataType : "json",
	    			    	success:function(data){
	    			    		if(data>0){
	    			    			toastr.success("删除成功！");
	    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	    								//关闭模态框
	    								// 父页面刷新
	    								window.location.reload();  
	    							},2000);
	    			    		}else{
	    			    			toastr.error("删除失败！");
	    			    		}
	    			    	}
	    			    })
	    		    	layer.close(index);
	    		  	});
	        	}
	      	break;
	      	case 'select':
	      		console.log(obj)
	      	break;
	    };
	});
	
	//监听子表的行工具事件(删除)
	table.on('tool(testDetial)', function(obj){
		var data = obj.data;
		console.log(obj)
		if(obj.event === 'del'){
		    var uid = obj.data.uid;
		  	$.ajax({
		  		type:'post',
		    	url:'${pageContext.request.contextPath }/teamMana/findTeamByUidInTeam.do',
		    	data:{"num":uid},
		    	dataType : "json",
		    	success:function(data){
		    		if(data > 0){
		    			toastr.warning("不能删除班组长！");
		    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
						},2000);
		    		}else{
		    			layer.confirm('确定删除吗？', function(index){
		    			    var tid = $('#tidtest').val();
		    			    $.ajax({
		    			    	type:'post',
		    			    	url:'${pageContext.request.contextPath }/teamMana/deleteUserInEmp.do',
		    			    	data:{"tid":tid, "uid":uid},
		    			    	dataType : "json",
		    			    	success:function(data){
		    			    		if(data>0){
		    			    			toastr.success("删除成功！");
		    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
		    								//关闭模态框
		    								// 父页面刷新
		    								window.location.reload();  
		    							},2000);
		    			    		}else{
		    			    			toastr.warning("删除失败！");
		    			    		}
		    			    	}
		    			    })
		    			    layer.close(index);
		    			  });
		    		}
		    	}
		  	});
		}
	});
	
	//头工具栏事件(班组表的新增，删除)
	table.on('toolbar(test)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
	    switch(obj.event){
	    	case 'add':
	    		layer.open({
					  type: 1 		//Page层类型
					  ,area: ['500px', '550px'] //宽  高
					  ,title: '新增'
					  ,shade: 0.1 	//遮罩透明度
					  ,shadeClose: true //点击遮罩关闭
					  ,maxmin: true //允许全屏最小化
					  ,anim: 1 		//0-6的动画形式，-1不开启
					  ,content: $('#formDiv')
					  ,success: function () {
						  document.getElementById("addform").reset();
					  }
					  ,end: function () {
						  var formDiv = document.getElementById('formDiv');
						  formDiv.style.display = '';
					  }
					});
	      	break;
	    	case 'delete':
	        	var data = checkStatus.data;
	        	var str = "";
	        	if(data.length==0){
	        		toastr.warning("请至少选择一条记录！");
	        	}
	        	for(var i=0;i<data.length;i++){
	        		str += data[i].tid;
	        		if(i != data.length-1){
	        			str += ",";
	        		}
	        	}
	        	$.ajax({
			    	type:'post',
			    	url:'${pageContext.request.contextPath }/teamMana/deleteTeamOfVerify.do',
			    	data:{"str":str},
			    	dataType : "json",
			    	success:function(data){
		    			layer.confirm('确定删除吗？', function(index){
		    				$.ajax({
		    			    	type:'post',
		    			    	url:'${pageContext.request.contextPath }/teamMana/deleteTeam.do',
		    			    	data:{"str":str},
		    			    	dataType : "json",
		    			    	success:function(data){
		    			    		if(data>0){
		    			    			toastr.success("删除成功！");
		    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
		    								//关闭模态框
		    								// 父页面刷新
		    								window.location.reload();  
		    							},2000);
		    			    		}else{
		    			    			toastr.error("删除失败！");
		    			    		}
		    			    	}
		    			    })
		    		    layer.close(index);
		    		  });
		    		}
			    })
	      	break;
	      	case 'select':
	      		console.log(obj)
	      	break;
	    };
	});
  
	//监听行工具事件（班组表格的删除，修改）
	table.on('tool(test)', function(obj){
		var data = obj.data;
		var tid = obj.data.tid;
		if(obj.event === 'del'){
			$.ajax({
		    	type:'post',
		    	url:'${pageContext.request.contextPath }/teamMana/deleteTeamOfVerify.do',
		    	data:{"str":tid},
		    	dataType : "json",
		    	success:function(data){
		    		layer.confirm('确定删除吗？', function(index){
	    				$.ajax({
	    			    	type:'post',
	    			    	url:'${pageContext.request.contextPath }/teamMana/deleteTeam.do',
	    			    	data:{"str":tid},
	    			    	dataType : "json",
	    			    	success:function(data){
	    			    		if(data>0){
	    			    			toastr.success("删除成功！");
	    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	    								//关闭模态框
	    								// 父页面刷新
	    								window.location.reload();  
	    							},2000);
	    			    		}else{
	    			    			toastr.error("删除失败！");
	    			    		}
	    			    	}
	    			    })
	    		    layer.close(index);
	    		  });
		    	}
		    })
		} else if(obj.event === 'edit'){
			layer.open({
				  type: 1 		//Page层类型
				  ,area: ['500px', '550px'] //宽  高
				  ,title: '编辑'
				  ,shade: 0.1 	//遮罩透明度
				  ,maxmin: true //允许全屏最小化
				  ,anim: 1 		//0-6的动画形式，-1不开启
				  ,content: $('#formDiv')
				  ,success: function () {
					//回显表单数据
					for(var i=0;i<Object.entries(data).length;i++) {
						var id = '#' + Object.entries(data)[i][0];
						var text = Object.entries(data)[i][1];
						$(id).val(text);
					}
					form.render();
				  }	
				  ,end: function () {
				  	var formDiv = document.getElementById('formDiv');
				  	formDiv.style.display = '';
			  	  }
			});
		}
	});
	/**
     * 表单校验
     */
   form.verify({
    	//value：表单的值、item：表单的DOM对象
    	 tname: function(value){
    		 var str = value.replace(/\s+/g,"");
    		 if(str == ''){
    			return '班组名称不能为空';
    		}
    	},
    	num: function(value){
    		var str = value.replace(/\s+/g,"");
    		if(str == ''){
    			return '班组长不能为空';
    		}
    	},
    });
	
	//获取班组长
	form.on('select(num)', function(data){
		$("#submit").attr("disabled",false); 
	});
	
    /**
     * 班组表（新增/修改）
     */
    form.on('submit(addform)', function (data) {
    	$("#submit").attr("disabled",true); 
    	$.ajax({
  			url : '${pageContext.request.contextPath }/teamMana/saveTeam.do',
  			data : $('#addform').serialize(),
  			type : "post",
  			dataType : "json",
  			}).done(
  				function(res) {
  					if (res > 0) {
  						if(res == 2){
  							toastr.success('新增成功！');
  						}
  						if(res == 3){
  							toastr.success('修改成功！');
  						}
  						setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
  							//关闭模态框
  							// 父页面刷新
  							window.location.reload();  
  						},2000);
  					}else{
  						toastr.warning("班组长或班组名称重复!");
  					}
  				}
  			).fail(
  				function(res) {
  					if(res == -2){
  						toastr.error('新增失败！');
  					}
  					if(res == -3){
  						toastr.error('修改失败！');
  					}
  				}
  			)
		return false;
    });
    
    /**
     * 员工表（新增/修改）
     */
    form.on('submit(addform2)', function (data) {
    	$("#submit").attr("disabled",true);
    	$.ajax({
   			url : '${pageContext.request.contextPath }/empMana/saveEmp.do',
   			data : $('#addform2').serialize(),
   			type : "post",
   			dataType : "json",
   			}).done(
   				function(res) {
   					if (res > 0) {
   						if(res == 2){
   							toastr.success('新增成功！');
   						}
   						if(res == 3){
   							toastr.success('修改成功！');
   						}
   						setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
   							//关闭模态框
   							// 父页面刷新
   							window.location.reload();
   						},2000);
   					}else{
   						toastr.warning("该员工已存在其他班组中!");
   					}
   				}
   			).fail(
   				function(res) {
   					if(res == -2){
   						toastr.error('新增失败！');
   					}
   					if(res == -3){
   						toastr.error('修改失败！');
   					}
   				}
   			)
		return false;
    });
    
});

function editValue(){
	$("#submit").attr("disabled",false); 
}

toastr.options.positionClass = 'toast-top-center'; //提示框的位置设置为中上
</script>
</body>
</html>